package org.devops

def ansibleExec(Map ipMap, ansibleName, deployIps, storeFileName, DEPLOY_DEST, remoteDir, REMOTE_COMMAND) {
    def nodeTools = new nodeTools()
    def ansibleIps = ipMap.get(ansibleName)
    def hosts = []
    for (ip in ansibleIps) {
        if (!deployIps.contains(ip)) {
            continue
        }
        hosts.add("- ${ip}")
    }

    if (hosts.size() > 0) {
        //执行ansible
        def hostsStr = hosts.join("\r\n  ")
        REMOTE_COMMAND = REMOTE_COMMAND.replaceAll("\n", "\n        ")
        //1.上传随机
        def deployYaml = """
- hosts: 
  ${hostsStr}
  user: root
  tasks:
  - name: 'createDir' 
    file: 
      path: ${DEPLOY_DEST}
      state: "directory"
      recurse: yes
  - name: 'copy2Host'
    copy: 
      src: /data/app_repos/${ENV}/${SERVICE}/${APP}/${remoteDir}/${storeFileName}
      dest: ${DEPLOY_DEST}
  - name: "decompression"
    shell: 
      chdir: ${DEPLOY_DEST}
      cmd: |
        tar -xf ${storeFileName}
  - name: "remoteCommand"
    shell:
      chdir: ${DEPLOY_DEST} 
      cmd: |
        ${REMOTE_COMMAND}
"""
        def randFile = "${ENV}-${SERVICE}-${APP}-${BUILD_NUMBER}.yaml"
        nodeTools.remoteExec(ansibleName, """
echo \"${deployYaml}\" > /tmp/${randFile}
ansible-playbook /tmp/${randFile} -v
rm -f /tmp/${randFile}
""")
    }
}


